<template>
    <div class="table-header">
        <el-button type="primary" @click="create">创建组件</el-button>
        <el-button type="primary" @click="query">刷新</el-button>
    </div>
    <el-table :data="state.tableData" stripe style="width: 100%">
        <el-table-column prop="name" label="组件名" width="180" />
        <el-table-column prop="name_es" label="唯一标识" width="180" />
        <el-table-column prop="icon" label="缩略图">
            <template #default="scope">
                <img :src="scope.row.icon" style="height: 60px;" />
            </template>
        </el-table-column>
        <el-table-column prop="classify_name" label="分类" width="120" />
        <el-table-column prop="version" label="当前版本" width="100" />

        <el-table-column label="操作">
            <template #default="scope">
                <div style="display:flex">
                    <el-upload :show-file-list="false" ref="uploadRef" :auto-upload="false" :on-change="uploadAssembly">
                        <template #trigger>
                            <el-button :loading="uploading" type="success" @click="uploadSelect(scope.row)">上传版本</el-button>
                        </template>
                    </el-upload>
                    <el-button style="margin-left: 8px;" type="danger" @click="delVersion(scope.row)">删除版本</el-button>
                    <el-button style="margin-left: 8px;" type="danger"
                        @click="delAssembly_sort(scope.row._id)">删除</el-button>
                </div>
            </template>
        </el-table-column>

    </el-table>

    <!-- 创建组件 -->
    <el-dialog width="500" v-model="dialogFormVisible" title="创建组件">
        <el-form :model="form" labelWidth="100">
            <el-form-item label="组件名">
                <el-select v-model="form.classify_id">
                    <el-option v-for="item in state.sortOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
                <el-popover placement="bottom" :width="200" trigger="click">
                    <template #reference>
                        <el-button style="margin-left: 8px;" type="primary">添加分类</el-button>
                    </template>
                    <el-input placeholder="请输入分类" v-model="classify"></el-input>
                    <div style="text-align: right; margin-top: 10px;">
                        <el-button type="primary" text bg @click="saveClassify">保存</el-button>
                    </div>
                </el-popover>

            </el-form-item>
            <el-form-item label="组件名">
                <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="组件标识">
                <el-input v-model="form.name_es" autocomplete="off" />
            </el-form-item>
            <el-form-item label="图标">
                <el-upload :auto-upload="false" :on-change="uploadIcon" v-model:file-list="fileList" list-type="picture">
                    <el-button type="primary">点击上传</el-button>
                    <template #tip>
                        <div class="el-upload__tip">
                            jpg/png files with a size less than 500kb
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="confirm">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 版本列表 -->
    <el-dialog v-model="dialogTableVisible" width="300px">
        <!-- <div>
            <el-button @click="delMult" type="danger">删除已选中</el-button>
        </div> -->
        <template #header="{ close, titleId, titleClass }">
            <div style="display: flex; align-items: center;">
                <h4 style="margin: 0;" :id="titleId" :class="titleClass">版本管理</h4>
                <el-button type="danger" style="margin-left: 12px;" @click="delMult()">
                    删除已选中
                </el-button>
            </div>
        </template>
        <el-table :data="state.gridData" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column property="version" label="版本号" />
        </el-table>
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { uploadFile } from '../../../request/index'
import { deleteAssembly_sort, queryAssemblyClassify, insertAssemblyClassify, deleteAssemblyFile, delAssembly, insertAssembly_sort, queryAssembly_sort, insertAssembly, queryAssembly, isExistVersion } from '../../../request/assembly'
import { ElMessage, ElMessageBox } from 'element-plus'
const state = reactive({
    tableData: [],
    gridData: [],
    sortOptions: []
})

const query = async () => {
    state.tableData = await queryAssembly_sort()
    console.log(state.tableData)
}
query()
const uploading = ref(false)
let selectedRow
const uploadSelect = (row) => {
    selectedRow = row
}
const uploadAssembly = (evt, row) => {
    const {
        name_es
    } = selectedRow
    const dir = name_es
    window.JSZip.loadAsync(evt.raw)                                   // 1) read the Blob
        .then(async function (zip) {
            const bolbArr = []
            let v
            let isUpdate = false
            for (let key in zip.files) {
                const content = await zip.file(key).async('blob')
                if (key === 'card.json') {
                    const f = new FileReader()
                    f.readAsText(content)
                    const cardJson = await new Promise((r) => {
                        f.onload = (e) => {
                            r(JSON.parse(e.target?.result))
                        }
                    })
                    // 查询版本是否存在
                    const { version } = cardJson
                    const { _id } = selectedRow
                    const isExist = await isExistVersion(_id, version)
                    if (isExist) {
                        isUpdate = true
                        await ElMessageBox.confirm(
                            '该版本组件已存在，是否覆盖？',
                            'Warning',
                            {
                                confirmButtonText: '覆盖',
                                cancelButtonText: '取消',
                                type: 'warning',
                            }
                        )
                    }
                    v = version
                }
                bolbArr.push(
                    {
                        dir: `cards/${dir}`,
                        key,
                        file: new File([content], name_es, { type: content.type })
                    }
                )
            }
            let count = 0
            let l = bolbArr.length
            uploading.value = true
            bolbArr.forEach(item => {
                uploadFile(`${item.dir}/${v}/${item.key}`, item.file).then(async () => {
                    count++
                    if (count === l) {
                        // 上传结束
                        // 添加记录
                        if (!isUpdate) {
                            await insertAssembly({
                                assembly_sort_id: selectedRow._id,
                                version: v
                            })
                            query()
                        }
                        uploading.value = false

                    }
                })
            })
        }, function (err) {
            console.log(err)
        });
}

// 创建组件
const dialogFormVisible = ref(false)
const form = reactive({
    classify_id: '',
    name: '',
    name_es: '',
    icon: ''
})
const delAssembly_sort = async (_id) => {
    await deleteAssembly_sort(_id)
    query()
}
const fileList = [
    // {
    //     name: '图标',
    //     url: form.icon
    // }
]
const querySortOptions = async () => {
    const res = await queryAssemblyClassify()
    state.sortOptions = res.map(item => {
        return {
            label: item.name,
            value: item._id
        }
    })
}

const create = () => {
    dialogFormVisible.value = true
    querySortOptions()
}
const confirm = async () => {
    await insertAssembly_sort(form)
    dialogFormVisible.value = false
    query()
}
const uploadIcon = async (evt) => {
    if (!form.name_es) {
        ElMessage.error('请先输入组件标识')
        return
    }
    const res = await uploadFile(`cards/${form.name_es}/icon`, evt.raw)
    form.icon = res.download_url
}

// 版本管理
const dialogTableVisible = ref(false)
const delVersion = async (row) => {
    selectedRow = row
    dialogTableVisible.value = true
    state.gridData = await queryAssembly(row._id)
}
let multipleSelection
const handleSelectionChange = (val) => {
    multipleSelection = val
}
const delMult = () => {
    // 删除记录
    delAssembly(selectedRow._id, multipleSelection.map(item => {
        return item.version
    }))
    // 删除对应文件
    deleteAssemblyFile(multipleSelection.map(item => {
        return `cards/${selectedRow.name_es}/${item.version}`
    }))
    dialogTableVisible.value = false
    console.log(multipleSelection)
}

// 组件分类
const classify = ref('')
const saveClassify = async () => {
    await insertAssemblyClassify({
        name: classify.value
    })
    classify.value = ''
    querySortOptions()
}
</script>
